<template>
  <div class="cart-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">
        <el-icon><ShoppingCart /></el-icon>
        购物车
      </h2>
      <p class="page-subtitle">确认您的订单信息</p>
    </div>

    <!-- 空购物车状态 -->
    <div v-if="!state.dish || state.dish.length === 0" class="empty-cart">
      <div class="empty-content">
        <div class="empty-icon">
          <el-icon><ShoppingCartFull /></el-icon>
        </div>
        <h3 class="empty-title">购物车空空如也</h3>
        <p class="empty-subtitle">快去选择您喜欢的商品吧</p>
        <el-button type="primary" size="large" @click="router.push('/home/rest')">
          <el-icon><Plus /></el-icon>
          去购物
        </el-button>
      </div>
    </div>

    <!-- 购物车内容 -->
    <div v-else-if="state.dish && state.dish.length > 0" class="cart-content">
      <!-- 商品列表 -->
      <div class="cart-items">
        <h3 class="section-title">
          <el-icon><List /></el-icon>
          商品清单 ({{ state.dish.length }}件)
        </h3>

        <div class="items-container">
          <el-card
            v-for="dish in state.dish"
            :key="dish.dish_id"
            class="cart-item-card"
            shadow="hover"
          >
            <div class="item-content">
              <div class="item-image">
                <img :src="dish.image_url" :alt="dish.dish_name" />
              </div>

              <div class="item-details">
                <h4 class="item-name">{{ dish.dish_name }}</h4>
                <p class="item-description">{{ dish.description }}</p>
                <div class="item-price">
                  <span class="price-symbol">¥</span>
                  <span class="price-value">{{ dish.price }}</span>
                </div>
              </div>

              <div class="item-controls">
                <div class="quantity-control">
                  <label class="control-label">数量</label>
                  <el-input-number
                    v-model="dish.count"
                    :min="1"
                    :max="10"
                    :step="1"
                    size="small"
                    @change="updateCount(dish.id, dish.count)"
                  />
                </div>

                <div class="item-total">
                  <span class="total-label">小计</span>
                  <span class="total-value">¥{{ (dish.price * dish.count).toFixed(2) }}</span>
                </div>

                <el-button
                  type="danger"
                  size="small"
                  text
                  @click="deleteOrder(dish.id)"
                  class="delete-btn"
                >
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </div>
            </div>
          </el-card>
        </div>
      </div>
      <!-- 订单摘要 -->
      <div v-if="!orderSubmitted" class="order-summary">
        <el-card class="summary-card" shadow="always">
          <template #header>
            <div class="summary-header">
              <h3>
                <el-icon><Money /></el-icon>
                订单摘要
              </h3>
            </div>
          </template>

          <!-- 价格明细 -->
          <div class="price-breakdown">
            <div class="price-item">
              <span class="price-label">商品总价</span>
              <span class="price-value">¥{{ safePrice.toFixed(2) }}</span>
            </div>

            <div v-if="couponInfo.totalDiscount > 0" class="price-item discount">
              <span class="price-label">优惠券折扣</span>
              <span class="price-value">-¥{{ couponInfo.totalDiscount.toFixed(2) }}</span>
            </div>

            <div class="price-divider"></div>

            <div class="price-item final">
              <span class="price-label">实付金额</span>
              <span class="price-value">¥{{ finalPrice.toFixed(2) }}</span>
            </div>
          </div>

          <!-- 优惠券选择 -->
          <div class="coupon-section">
            <CouponSelector
              :order-amount="safePrice"
              :user-id="user_id"
              @coupon-change="handleCouponChange"
              ref="couponSelectorRef"
            />
          </div>
        </el-card>
      </div>

      <!-- 配送信息 -->
      <div class="delivery-info">
        <el-card class="delivery-card" shadow="hover">
          <template #header>
            <div class="delivery-header">
              <h3>
                <el-icon><Location /></el-icon>
                配送信息
              </h3>
            </div>
          </template>

          <el-form
            :model="orderForm"
            label-width="80px"
            class="delivery-form"
            :rules="formRules"
            ref="formRef"
          >
            <el-form-item label="收货人" prop="username">
              <el-input
                v-model="orderForm.username"
                placeholder="请输入收货人姓名"
                prefix-icon="User"
              />
            </el-form-item>

            <el-form-item label="配送地址" prop="address">
              <el-input
                v-model="orderForm.address"
                placeholder="请输入详细配送地址"
                prefix-icon="Location"
                type="textarea"
                :rows="2"
              />
            </el-form-item>

            <el-form-item label="联系电话" prop="contact">
              <el-input
                v-model="orderForm.contact"
                placeholder="请输入联系电话"
                prefix-icon="Phone"
              />
            </el-form-item>

            <el-form-item label="订单备注">
              <el-input
                v-model="orderForm.beizhu"
                placeholder="如有特殊要求请在此说明（选填）"
                type="textarea"
                :rows="2"
                maxlength="100"
                show-word-limit
              />
            </el-form-item>
          </el-form>
        </el-card>
      </div>

      <!-- 提交按钮 -->
      <div class="submit-section">
        <div class="submit-info">
          <div class="balance-info">
            <span class="balance-label">账户余额：</span>
            <span class="balance-value">¥{{ safeBalance.toFixed(2) }}</span>
          </div>
          <div class="final-amount">
            <span class="amount-label">需支付：</span>
            <span class="amount-value">¥{{ finalPrice.toFixed(2) }}</span>
          </div>
        </div>

        <el-button
          v-if="!orderSubmitted"
          type="primary"
          size="large"
          @click="submitFn"
          :loading="submitting"
          :disabled="!canSubmit"
          class="submit-btn"
        >
          <el-icon><Check /></el-icon>
          确认下单
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from 'element-plus';
import {
  getOrdersApi,
  deleteOrderApi,
  updateOrderApi,
  orderApi,
  addExpenditureApi,
  calculateTotalAmountApi,
} from "@/utils/api";
import CouponSelector from '@/components/CouponSelector.vue';
import {
  ShoppingCart,
  ShoppingCartFull,
  Plus,
  List,
  Delete,
  Money,
  Location,
  User,
  Phone,
  Check
} from '@element-plus/icons-vue';

const router = useRouter();

const state = ref({
  dish: [],
  price: 0
});
const orderSubmitted = ref(false);
const resultmoney = ref(0);
const couponSelectorRef = ref(null);
const formRef = ref(null);
const submitting = ref(false);

// 优惠券相关数据
const couponInfo = ref({
  coupons: [],
  totalDiscount: 0,
  finalAmount: 0,
  couponCodes: []
});

// 获取用户ID
const user_id = JSON.parse(localStorage.getItem("user")).user_id;

const orderForm = ref({
  username: "",
  address: "",
  contact: "",
  beizhu: "",
});

// 表单验证规则
const formRules = {
  username: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入配送地址', trigger: 'blur' },
    { min: 5, max: 100, message: '地址长度在 5 到 100 个字符', trigger: 'blur' }
  ],
  contact: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
};

// 安全的价格计算
const safePrice = computed(() => {
  return Number(state.value.price) || 0;
});

// 安全的余额计算
const safeBalance = computed(() => {
  return Number(resultmoney.value) || 0;
});

// 计算最终价格
const finalPrice = computed(() => {
  return Math.max(0, safePrice.value - couponInfo.value.totalDiscount);
});

// 检查是否可以提交
const canSubmit = computed(() => {
  return orderForm.value.username &&
         orderForm.value.address &&
         orderForm.value.contact &&
         safeBalance.value >= finalPrice.value &&
         !submitting.value;
});

const init = async () => {
  try {
    const data = JSON.parse(localStorage.getItem("user"));
    const user_id = data.user_id;

    const balanceRes = await calculateTotalAmountApi({ user_id });
    resultmoney.value = balanceRes.data;


    const ordersRes = await getOrdersApi({ user_id });
    if (ordersRes.code === 200) {
      const userInfo = ordersRes.data[0][0];
      let orderItems = ordersRes.data[1];

      orderItems = orderItems.filter((item) => item.CartStatus !== 0);
      orderSubmitted.value = orderItems.length === 0;

      const totalPrice = orderItems
        .reduce((total, item) => total + item.price * item.count, 0)
        .toFixed(2);

      state.value = {
        user: userInfo,
        dish: orderItems,
        price: totalPrice,
        image_url: orderItems.length > 0 ? orderItems[0].image_url : "",
      };
    }
  } catch (error) {
    console.error("初始化失败:", error);
    alert("初始化失败，请稍后重试！");
  }
};

init();

const updateCount = async (id, count) => {
  try {
    const res = await updateOrderApi({ id, count });
    console.log(res);
    await init();
  } catch (error) {
    console.error("更新数量失败:", error);
    alert("更新数量失败，请稍后重试！");
  }
};

const deleteOrder = async (id) => {
  try {
    const confirmDelete = confirm("确定删除吗？");
    if (!confirmDelete) return;

    const res = await deleteOrderApi({ id });
    console.log(res);
    await init();
  } catch (error) {
    console.error("删除订单失败:", error);
    alert("删除订单失败，请稍后重试！");
  }
};

// 处理优惠券变化
const handleCouponChange = (couponData) => {
  couponInfo.value = couponData;
  console.log('优惠券信息更新:', couponData);
};

const submitFn = async () => {
  // 表单验证
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
  } catch (error) {
    ElMessage.warning('请完善订单信息');
    return;
  }

  // 余额检查
  if (safeBalance.value < finalPrice.value) {
    ElMessage.error("余额不足，请充值后再提交订单！");
    return;
  }

  try {
    submitting.value = true;
    const userData = JSON.parse(localStorage.getItem("user"));
    const order_date = new Date().toLocaleDateString();
    const final_price = finalPrice.value;
    const dish = state.value.dish;

    await orderApi({
      user_id: userData.user_id,
      order_date,
      total_price: final_price,
      order_status: "已提交",
      dish,
      username: orderForm.value.username,
      address: orderForm.value.address,
      contact: orderForm.value.contact,
      beizhu: orderForm.value.beizhu || "无",
      coupon_codes: couponInfo.value.couponCodes,
    });

    await addExpenditureApi({
      date: order_date,
      amount: final_price,
      user_id: userData.user_id,
    });

    // 清空优惠券选择
    if (couponSelectorRef.value) {
      couponSelectorRef.value.clearSelection();
    }
    couponInfo.value = {
      coupons: [],
      totalDiscount: 0,
      finalAmount: 0,
      couponCodes: []
    };

    orderSubmitted.value = true;
    await init();

    ElMessage.success("订单提交成功！");
    if (couponInfo.value.totalDiscount > 0) {
      ElMessage.success(`已为您节省 ¥${couponInfo.value.totalDiscount.toFixed(2)}`);
    }

    setTimeout(() => {
      router.push("/home/order");
    }, 1500);
  } catch (error) {
    console.error("提交订单失败:", error);
    ElMessage.error("提交订单失败，请稍后重试！");
  } finally {
    submitting.value = false;
  }
};
</script>

<style lang="less" scoped>
.cart-page {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.page-header {
  margin-bottom: 24px;

  .page-title {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin: 0 0 8px 0;

    .el-icon {
      color: #409eff;
    }
  }

  .page-subtitle {
    color: #909399;
    margin: 0;
    font-size: 14px;
  }
}

// 空购物车样式
.empty-cart {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;

  .empty-content {
    text-align: center;

    .empty-icon {
      font-size: 80px;
      color: #e4e7ed;
      margin-bottom: 20px;
    }

    .empty-title {
      font-size: 18px;
      color: #303133;
      margin: 0 0 8px 0;
    }

    .empty-subtitle {
      color: #909399;
      margin: 0 0 24px 0;
    }
  }
}

// 购物车内容样式
.cart-content {
  display: grid;
  grid-template-columns: 1fr 400px;
  gap: 24px;

  @media (max-width: 1200px) {
    grid-template-columns: 1fr;
  }
}

.cart-items {
  .section-title {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 18px;
    font-weight: 600;
    color: #303133;
    margin: 0 0 16px 0;

    .el-icon {
      color: #409eff;
    }
  }
}

.items-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.cart-item-card {
  border: none;
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
  }

  :deep(.el-card__body) {
    padding: 20px;
  }
}

.item-content {
  display: flex;
  gap: 16px;
  align-items: flex-start;
}

.item-image {
  width: 100px;
  height: 100px;
  border-radius: 8px;
  overflow: hidden;
  flex-shrink: 0;

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.item-details {
  flex: 1;

  .item-name {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    margin: 0 0 8px 0;
  }

  .item-description {
    font-size: 14px;
    color: #909399;
    margin: 0 0 12px 0;
    line-height: 1.4;
  }

  .item-price {
    display: flex;
    align-items: baseline;

    .price-symbol {
      font-size: 14px;
      color: #f56c6c;
    }

    .price-value {
      font-size: 18px;
      font-weight: 600;
      color: #f56c6c;
    }
  }
}

.item-controls {
  display: flex;
  flex-direction: column;
  gap: 12px;
  align-items: flex-end;
  min-width: 120px;

  .quantity-control {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 4px;

    .control-label {
      font-size: 12px;
      color: #909399;
    }
  }

  .item-total {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 4px;

    .total-label {
      font-size: 12px;
      color: #909399;
    }

    .total-value {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }
  }

  .delete-btn {
    color: #f56c6c;

    &:hover {
      background: #fef0f0;
    }
  }
}

// 订单摘要样式
.order-summary {
  position: sticky;
  top: 20px;
  height: fit-content;
}

.summary-card {
  border: none;
  border-radius: 12px;
  overflow: hidden;

  :deep(.el-card__header) {
    background: #fafbfc;
    border-bottom: 1px solid #ebeef5;
  }

  .summary-header h3 {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    margin: 0;

    .el-icon {
      color: #409eff;
    }
  }
}

.price-breakdown {
  margin-bottom: 20px;

  .price-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;

    &:last-child {
      margin-bottom: 0;
    }

    .price-label {
      font-size: 14px;
      color: #606266;
    }

    .price-value {
      font-size: 14px;
      color: #303133;
      font-weight: 500;
    }

    &.discount {
      .price-value {
        color: #f56c6c;
      }
    }

    &.final {
      padding-top: 12px;
      border-top: 1px solid #ebeef5;

      .price-label {
        font-size: 16px;
        font-weight: 600;
        color: #303133;
      }

      .price-value {
        font-size: 18px;
        font-weight: 600;
        color: #f56c6c;
      }
    }
  }
}

.price-divider {
  height: 1px;
  background: #ebeef5;
  margin: 12px 0;
}

.coupon-section {
  border-top: 1px solid #ebeef5;
  padding-top: 20px;
}

// 配送信息样式
.delivery-info {
  margin-top: 24px;
}

.delivery-card {
  border: none;
  border-radius: 12px;
  overflow: hidden;

  :deep(.el-card__header) {
    background: #fafbfc;
    border-bottom: 1px solid #ebeef5;
  }

  .delivery-header h3 {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    margin: 0;

    .el-icon {
      color: #409eff;
    }
  }
}

.delivery-form {
  :deep(.el-form-item) {
    margin-bottom: 20px;
  }

  :deep(.el-form-item__label) {
    font-weight: 500;
    color: #303133;
  }
}

// 提交区域样式
.submit-section {
  margin-top: 24px;
  padding: 20px;
  background: #fff;
  border-radius: 12px;
  border: 1px solid #ebeef5;

  .submit-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    .balance-info, .final-amount {
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .balance-label, .amount-label {
      font-size: 14px;
      color: #606266;
    }

    .balance-value {
      font-size: 14px;
      color: #67c23a;
      font-weight: 600;
    }

    .amount-value {
      font-size: 18px;
      color: #f56c6c;
      font-weight: 600;
    }
  }

  .submit-btn {
    width: 100%;
    height: 48px;
    font-size: 16px;
    font-weight: 600;
    border-radius: 8px;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .cart-page {
    padding: 16px;
  }

  .item-content {
    flex-direction: column;
    gap: 12px;
  }

  .item-image {
    width: 80px;
    height: 80px;
    align-self: center;
  }

  .item-controls {
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    min-width: auto;
    width: 100%;
  }

  .submit-info {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
}
</style>
